package com.wnxy.sddfp.system.mq;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wnxy.sddfp.common.constant.MQConstant;
import com.wnxy.sddfp.common.model.dto.bank.BankCardRequestDto;
import com.wnxy.sddfp.system.entity.UserCard;
import com.wnxy.sddfp.system.entity.UserDetail;
import com.wnxy.sddfp.system.service.IUserCardService;
import com.wnxy.sddfp.system.service.IUserDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

/**
 * 消费者监听器：
 * 1、监听队列消息：sddf-queue-account
 * 2、消息内容：{"reqCode":"","userCode":"","bankNo":"","bankTitle":""}
 * 3、对象封装消息内容：BankCardRequestDto
 * 4、处理业务
 * A、更新用户详情绑卡状态
 * B、更新用户绑卡信息表; u_user_card
 */
//@Component
@Slf4j
public class BindResultConsumer {
    @Autowired
    private IUserDetailService userDetailService;
    @Autowired
    private IUserCardService userCardService;

    /**
     * 监听队列sddf-queue-account的消息
     *
     * @Payload 注解
     * 1、注解实现把消息的json内容转换为对象
     * 2、注意：要配置消息的转换器
     */
    @RabbitListener(queues = MQConstant.SDDF_QUEUE_ACCOUNT)
    public void handlerMsg(@Payload BankCardRequestDto bankCardRequestDto) {
        log.debug("消费者监听队列消息，绑卡结果数据：{}", bankCardRequestDto);

        //A、更新用户详情绑卡状态; 更新条件：reqCode
        userDetailService.update(Wrappers.lambdaUpdate(UserDetail.class)
                .set(UserDetail::getCardBindStatus, true)
                .eq(UserDetail::getReqCode, bankCardRequestDto.getReqCode())
        );

        //B、更新用户绑卡信息表; u_user_card
        //B1、根据reqCode查询，获取用户对象（用户ID）
        UserDetail userDetail = userDetailService.getOne(Wrappers.lambdaQuery(UserDetail.class)
                .select(UserDetail::getId)  // 指定查询列： select id from u_user_detail
                .eq(UserDetail::getReqCode, bankCardRequestDto.getReqCode())
        );
        //B2、根据用户ID，更新用户绑卡记录
        userCardService.update(Wrappers.lambdaUpdate(UserCard.class)
                .set(UserCard::getBankNo,bankCardRequestDto.getBankNo())
                .set(UserCard::getBankTitle,bankCardRequestDto.getBankTitle())
                .eq(UserCard::getUserId,userDetail.getId())
        );
    }
}
